<template>
  <div class="login-register">
    <div class="contain">
      <div
        class="big-box"
        :class="{ active: isLogin }"
      >
        <div
          v-if="isLogin"
          class="big-contain"
        >
          <div>
            <div class="btitle">
              账户登录
            </div>
            <div class="bform">
              <div class="login-from-box">
                <a-form-model
                  ref="form"
                  :model="model"
                  :rules="validatorRules"
                >
                  <a-form-model-item
                    required
                    prop="username"
                  >
                    <a-input
                      v-model="model.username"
                      placeholder="请输入用户名或邮箱"
                    >
                      <a-icon
                        slot="prefix"
                        type="user"
                        :style="{ color: 'rgba(0,0,0,.25)' }"
                      />
                    </a-input>
                  </a-form-model-item>
                  <a-form-model-item
                    required
                    prop="password"
                  >
                    <a-input-password
                      v-model="model.password"
                      autocomplete="false"
                      placeholder="请输入密码"
                    >
                      <a-icon
                        slot="prefix"
                        type="lock"
                        :style="{ color: 'rgba(0,0,0,.25)' }"
                      />
                    </a-input-password>
                  </a-form-model-item>

                  <a-row :gutter="0">
                    <a-col :span="11">
                      <a-form-model-item
                        required
                        prop="captcha"
                      >
                        <a-input
                          v-model="model.captcha"
                          style="width: 100px"
                          type="text"
                          placeholder="验证码"
                        >
                          <a-icon
                            slot="prefix"
                            type="smile"
                            :style="{ color: 'rgba(0,0,0,.25)' }"
                          />
                        </a-input>
                      </a-form-model-item>
                    </a-col>

                    <a-col :span="11">
                      <img
                        v-if="requestCodeSuccess"
                        class="captcha-code"
                        :src="captchaPath"
                        @click="updateVerifyCode()"
                      >
                      <img
                        v-else
                        class="captcha-code"
                        src="@/assets/images/checkcode.png"
                        @click="updateVerifyCode"
                      >
                    </a-col>
                  </a-row>
                  <a-form-model-item>
                    <a-button
                      block
                      type="primary"
                      html-type="submit"
                      class="btnLogin"
                      :loading="loading"
                      @click.stop.prevent="login"
                    >
                      确定
                    </a-button>
                  </a-form-model-item>
                </a-form-model>
              </div>
            </div>
          </div>
        </div>
        <div
          v-else
          class="big-contain"
        >
          <div class="regist-btitle">
            创建账户
          </div>
          <div class="bform-regist">
            <div class="login-from-box">
              <a-form-model
                ref="formRegist"
                :model="regist"
                :rules="validatorRulesRegist"
              >
                <a-form-model-item
                  required
                  prop="useremail"
                >
                  <a-input
                    v-model="regist.useremail"
                    placeholder="请输入邮箱地址"
                  >
                    <a-icon
                      slot="prefix"
                      type="user"
                      :style="{ color: 'rgba(0,0,0,.25)' }"
                    />
                  </a-input>
                </a-form-model-item>

                <a-row :gutter="0">
                  <a-col :span="11">
                    <a-form-model-item
                      required
                      prop="captcha"
                    >
                      <a-input
                        v-model="regist.captcha"
                        style="width: 100px"
                        type="text"
                        placeholder="验证码"
                      >
                        <a-icon
                          slot="prefix"
                          type="smile"
                          :style="{ color: 'rgba(0,0,0,.25)' }"
                        />
                      </a-input>
                    </a-form-model-item>
                  </a-col>

                  <a-col :span="11">
                    <a-button
                      class="captcha-code btnLogin"
                      :disabled="state.smsSendBtn"
                      @click="getCaptcha"
                      v-text="!state.smsSendBtn ? '获取验证码' : (state.time+' s')"
                    />
                  </a-col>
                </a-row>
                <a-form-model-item
                  required
                  prop="password"
                >
                  <a-input
                    v-model="regist.password"
                    type="password"
                    autocomplete="false"
                    placeholder="请输入密码"
                  >
                    <a-icon
                      slot="prefix"
                      type="lock"
                      :style="{ color: 'rgba(0,0,0,.25)' }"
                    />
                  </a-input>
                </a-form-model-item>
                <a-form-model-item
                  required
                  prop="againpwd"
                >
                  <a-input-password
                    v-model="regist.againpwd"
                    autocomplete="false"
                    placeholder="请再次输入密码"
                  >
                    <a-icon
                      slot="prefix"
                      type="lock"
                      :style="{ color: 'rgba(0,0,0,.25)' }"
                    />
                  </a-input-password>
                </a-form-model-item>
                <a-form-model-item>
                  <a-button
                    block
                    type="primary"
                    html-type="submit"
                    class="btnLogin"
                    :loading="loading"
                    @click.stop.prevent="register()"
                  >
                    确定
                  </a-button>
                </a-form-model-item>
              </a-form-model>
            </div>
          </div>
        </div>
      </div>
      <div
        class="small-box"
        :class="{ active: isLogin }"
      >
        <div
          v-if="isLogin"
          class="small-contain"
        >
          <div class="stitle">
            你好，朋友!
          </div>
          <p class="scontent">
            开始注册，和我们一起旅行
          </p>
          <button
            class="sbutton"
            @click="changeType"
          >
            注册
          </button>
        </div>
        <div
          v-else
          class="small-contain"
        >
          <div class="stitle">
            欢迎回来!
          </div>
          <p class="scontent">
            与我们保持联系，请登录你的账户
          </p>
          <button
            class="sbutton"
            @click="changeType"
          >
            登录
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { doLogin, register, getVerify, getEmailVerify, checkUserEmail } from '@/api/api'
import { hex_md5 } from '@/util/md5'
export default {
  name: 'LoginRegister',
  data () {
    return {
      requestCodeSuccess: false,
      model: {
        username: '',
        password: '',
        captcha: ''
      },
      regist: {
        useremail: '',
        captcha: '',
        password: '',
        againpwd: ''
      },
      state: {
        time: 60,
        smsSendBtn: false
      },
      loading: false,
      isLogin: true,
      captchaPath: '',
      validatorRules: {
        username: [
          { required: true, message: '请输入用户名!' },
          { validator: this.handleUsernameOrEmail }
        ],
        password: [
          {
            required: true,
            message: '请输入密码!',
            validator: 'click'
          }
        ],
        captcha: [
          {
            required: true,
            message: '请输入验证码!'
          }
        ]
      },
      validatorRulesRegist: {
        useremail: [
          { required: true, message: '请输入邮箱!' }
        ],
        password: [
          {
            required: true,
            message: '请输入密码!',
            validator: 'click'
          }
        ],
        againpwd: [
          {
            required: true,
            message: '请输入密码!',
            validator: 'click'
          }
        ],
        captcha: [
          {
            required: true,
            message: '请输入验证码!'
          }
        ]
      }
    }
  },
  mounted () {
    if (this.isLogin) {
      this.updateVerifyCode()
    }
  },
  methods: {
    // 获取验证码
    getCaptcha () {
      const that = this
      that.validateFields('formRegist', ['useremail'], (err) => {
        if (!err) {
          // 校验邮箱是否已经注册
          checkUserEmail(that.regist.useremail).then((res) => {
            if (res.code === 20000) {
              that.$message.error(res.message)
            } else {
              that.state.smsSendBtn = true
              const interval = window.setInterval(() => {
                if (that.state.time-- <= 0) {
                  that.state.time = 60
                  that.state.smsSendBtn = false
                  window.clearInterval(interval)
                }
              }, 1000)
              const hide = that.$message.loading('验证码发送中..', 0)
              getEmailVerify(this.regist.useremail)
                .then((res) => {
                  if (res.code === 200) {
                    setTimeout(hide, 0)
                    // that.state.smsSendBtn = false;
                    that.$message.success(res.data)
                  }
                  setTimeout(hide, 500)
                })
                .catch((err) => {
                  setTimeout(hide, 1)
                  clearInterval(interval)
                  that.state.time = 60
                  that.state.smsSendBtn = false
                  that.$message.error(err)
                })
            }
          })
        }
      }
      )
    },
    changeType () {
      this.isLogin = !this.isLogin
      // this.form.username = "";
      // this.form.useremail = "";
      // this.form.userpwd = "";
    },
    updateVerifyCode () {
      getVerify(Date.parse(new Date())).then((res) => {
        (this.requestCodeSuccess = true), (this.captchaPath = res.data)
      })
    },
    login () {
      this.validateFields('form', ['username', 'password', 'captcha'], (valid) => {
        if (!valid) {
          this.loading = true
          const captchaKey = localStorage.getItem('captchaKey')
          const user = {
            userName: this.model.username,
            password: hex_md5(this.model.password)
          }
          doLogin(this.model.captcha, captchaKey, user)
            .then((res) => {
              if (res.code === 200) {
                this.loading = false
                const redirect = this.$route.query.redirect
                console.log('redirect == ' + redirect)
                if (redirect) {
                  location.href = redirect
                } else {
                  location.href = '/'
                }
              } else {
                this.$message.error(res.message)
                this.loading = false
              }
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    register () {
      const that = this
      this.validateFields('formRegist', ['useremail', 'captcha', 'password', 'againpwd'], (valid) => {
        if (!valid) {
          // 判断是否填写验证码
          if (!that.regist.captcha) {
            that.$message.error('请您填写验证码!')
          }
          // TODO 采用滑块验证
          const user = {
            email: that.regist.useremail,
            password: hex_md5(that.regist.password)
          }
          register(that.regist.captcha, user).then((res) => {
            if (res.code === 200) {
              that.$message.success(res.data)
              that.isLogin = true
            } else {
              that.$message.error(res.message)
            }
          })
        }
      })
    },
    /**
         * 验证字段
         * @param arr
         * @param callback
         */
    validateFields (formName, arr, callback) {
      const promiseArray = []
      for (const item of arr) {
        const p = new Promise((resolve, reject) => {
          this.$refs[formName].validateField(item, (err) => {
            if (!err) {
              resolve()
            } else {
              reject(err)
            }
          })
        })
        promiseArray.push(p)
      }
      Promise.all(promiseArray)
        .then(() => {
          callback()
        })
        .catch((err) => {
          callback(err)
        })
    }
  }
}
</script>

<style scoped="scoped">
.captcha-code {
    margin-top: 4px;
    cursor: pointer;
    width: 100px;
    height: 33px;
    margin-left: 10px;
    border: solid 1px rgb(194, 193, 193);
    border-radius: 10px;
}
.login-register {
    width: 1249px;
    height: 100vh;
    margin: 10px auto;
    box-sizing: border-box;
    background: var(--bg-color);
    background-size: 100%;
    background-repeat: no-repeat;
}
.contain {
    width: 60%;
    height: 70%;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgb(255, 252, 252);

    border-radius: 20px;
    /* box-shadow: 0 0 3px #f0f0f0, 0 0 6px #f0f0f0; */
}
.big-box {
    width: 70%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 30%;
    transform: translateX(0%);
    transition: all 1s;
}
.big-contain {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.btitle {
    margin-top: 100px;
    text-align: center;
    font-size: 1.5em;
    font-weight: bold;
    color: var(--special-color);
}
.regist-btitle {
    margin-top: -7px;
    text-align: center;
    font-size: 1.5em;
    font-weight: bold;
    color: var(--text-color);
}
.bform {
    margin-top: 50px;
    width: 100%;
    height: 50%;
    padding: 2em 0;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
}
.bform-regist {
    margin-top: 70px;
    width: 100%;
    height: 50%;
    padding: 2em 0;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
}
.bform login-from-box {
    margin-top: -300px;
    text-align: center;
    width: 150px;
}
.bform regist-from-box {
    margin-top: 90px;
    text-align: center;
    width: 150px;
}
.btnLogin {
    background-color: var(--special-color);
    border-radius: 24px;
}
.small-box {
    width: 30%;
    height: 100%;
    background: linear-gradient(
        135deg,
        var(--special-color),
        var(--special-color)
    );
    position: absolute;
    top: 0;
    left: 0;
    transform: translateX(0%);
    transition: all 1s;
    border-top-left-radius: inherit;
    border-bottom-left-radius: inherit;
}
.small-contain {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.stitle {
    font-size: 1.5em;
    font-weight: bold;
    color: #fff;
}
.scontent {
    font-size: 0.8em;
    color: #fff;
    text-align: center;
    padding: 2em 4em;
    line-height: 1.7em;
}
.sbutton {
    width: 60%;
    height: 40px;
    border-radius: 24px;
    border: 1px solid #fff;
    outline: none;
    background-color: transparent;
    color: #fff;
    font-size: 0.9em;
    cursor: pointer;
}
.big-box.active {
    left: 0;
    transition: all 0.5s;
}
.small-box.active {
    left: 100%;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    border-top-right-radius: inherit;
    border-bottom-right-radius: inherit;
    transform: translateX(-100%);
    transition: all 1s;
}
</style>
